
const usedServer = /webpack-dev-server/.test(process.argv[1]);
const isDevelopment = (process.env.NODE_ENV || '').toLowerCase().substr(0, 3) === 'dev' || usedServer;
process.env.NODE_ENV = isDevelopment ? 'development' : 'production';

const pathFn = require('path');
const fsFn = require('fs');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const ExtractCssPlugin = require(usedServer ? 'extract-css-chunks-webpack-plugin' : 'mini-css-extract-plugin');

const loaders = {
	eslint: 'eslint-loader',
	vue: 'vue-loader',
	babel: 'babel-loader',
	less: 'less-loader',
	sass: 'sass-loader',
	postcss: 'postcss-loader',
	style: 'style-loader',
	css: {loader: 'css-loader', options: { modules: { localIdentName: '[local]' } } },
	cssModule: {loader: 'css-loader', options: { modules: { localIdentName: '[local]--[contenthash:base64:8]' } } },
	extractCss: {loader: ExtractCssPlugin.loader, options: {hot: true, reloadAll: false}},
	file: {loader: 'file-loader', options: {name: '[path][name].[ext]'}},
};

// source map 生成方式
const devtool = process.env.DEVTOOL || 'source-map';
// 是否开启文件监听
let watch = isDevelopment;
if (process.env.WATCH_FILE) {
	const watchFile = process.env.WATCH_FILE.toLowerCase();
	if (watchFile === '1' || watchFile === 'yes' || watchFile === 'true') {
		watch = true;
	} else if (watchFile === '0' || watchFile === 'no' || watchFile === 'false') {
		watch = false;
	}
}
function removeFiles(path) {
	if(!fsFn.existsSync(path)) { return; }
	if(!fsFn.statSync(path).isDirectory()) {
		console.log('rm', pathFn.relative('.', path));
		try { fsFn.unlinkSync(path); } catch { }
		return;
	}
	for (let file of fsFn.readdirSync(path)){
		removeFiles(pathFn.resolve(path, file));
	}
	console.log('rmdir', pathFn.relative('.', path));
	try { fsFn.rmdirSync(path); } catch { }
}
for (let file of fsFn.readdirSync('./dist')){
	if (file === 'index.html') { continue; }
	removeFiles(pathFn.resolve('./dist', file));
}

const config = {
	mode: isDevelopment ? 'development' : 'production',
	devtool, watch,
	context: pathFn.resolve(__dirname, 'src'),
	entry: {
		// 因为 context 配置为 src 目录，所以这里直接相对于 src 目录的路径就可以
		index: './index',
	},
	output: {
		path: pathFn.resolve(__dirname, 'dist'),
		filename: '[name].js',
		chunkFilename: '[name].[id].js',
	},
	module: {
		rules: [
			{ test: /(.jpg|.jpeg|.png|.gif|.tiff|.ico|.svg|.eot|.otf|.ttf|.woff|.woff2)$/i, use: loaders.file },

			{ test: /\.(css|less|scss|sass)$/, use: isDevelopment ? loaders.style : loaders.extractCss },
			{ test: /\.module\.(css|less|scss|sass)$/, use: loaders.cssModule },
			{ test: /(?<!\.module)\.(css|less|scss|sass)$/, use: loaders.css },
			{ test: /\.(css|less|scss|sass)$/, use: loaders.postcss },
			{ test: /\.less$/, use: loaders.less },
			{ test: /\.(scss|sass)$/, use:loaders.sass },
			
			{ test: /\.(js|jsx|ts|tsx|mjs|es)$/, use: loaders.babel },
			{ test: /\.(js|jsx|ts|tsx|mjs|es|vue)$/, enforce:'pre', use: loaders.eslint, exclude: /node_modules/ },
			{ test: /\.vue$/, loader: loaders.vue },
		].filter(Boolean),
	},
	plugins: [
		new ExtractCssPlugin({
			filename: '[name].css',
			chunkFilename: '[name].[id].css',
		}),
		new VueLoaderPlugin(),
	],
	resolve: {
		extensions: [
			'.tsx', '.ts', '.vue',
			'.jsx', '.mjs', '.js',
			'.less', '.scss', '.sass', '.css',
			'.module.less', '.module.scss', '.module.sass', '.module.css',
			'.png', '.svg', '.gif', '.jpeg', '.jpg',
		],
		modules: [ 'node_modules' ],
		alias: {
			// 路径别名，如果使用 TypeScript, tsconfig.json 中的 compilerOptions.paths 需要与此处同步配置
			'@': pathFn.resolve(__dirname, 'src'),
		},
	},
	watchOptions: {
		ignored: /node_modules/,
		// poll: 1000,
	},
	devServer: {
		contentBase: pathFn.join(__dirname, 'dist'),
		compress: false,
		port: 8080,
		historyApiFallback: true,
		host: '0.0.0.0',
		hot: true,
	},
};

module.exports = usedServer ? new Promise(resolve => setTimeout(resolve, 200, config)) : config;

if (usedServer) { console.log(`
\x1B[1;3;5;32m

服务器启动后，可以通过以下路径访问：

\x1B[4;33m

	http://0.0.0.0:${config.devServer.port}/

\x1B[24;34m
                            by 开发者王晨旭
                               http://www.wangchenxu.net/

\x1B[0m
`); }
